﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;

namespace BitPortal.Admin.Feedback.Module
{
    public partial class ReplyFeedback : Controls.BaseAdminControl
    {
        public List<Models.Feedback> ListFeedbacks = new List<Models.Feedback>();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void BindData()
        {
            txtTo.Text = "";
            txtIDs.Text = "";
            if (ListFeedbacks != null)
            {
                foreach (Models.Feedback feed in ListFeedbacks)
                {
                    txtTo.Text += feed.SenderEmail + ";";
                    txtIDs.Text += feed.FeedbackID + ";";
                }
            }
            Window1.Show();
        }

        protected void btnReply_Click(object sender, DirectEventArgs e)
        {
            try
            {
                //PermissionBLL.CheckRoleThrowException("CustomerView");
                foreach (string email in txtTo.Text.Split(';').Where(str => !String.IsNullOrEmpty(str)))
                {
                    try
                    {
                        EmailUtils.SendEmail(from: txtFrom.Text, to: email, subject: txtSubject.Text, body: txtContent.Text, smtpServer: PortalConfigBLL.GetValueByName("Email.SMTPServer").ToString());
                    }
                    catch { }
                }
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                foreach (string id in txtIDs.Text.Split(';'))
                {
                    long feedID = id.ToInt64TryParse();
                    Models.Feedback feed = bitEnt.Feedbacks.SingleOrDefault(ent => ent.FeedbackID == feedID);
                    if (feed != null)
                    {
                        feed.RepliedUser = BitContext.Current.LoginUser;
                        feed.DatetimeReplied = DateTime.Now;
                        feed.IsReplied = true;
                    }
                }
                int record = bitEnt.SaveChanges();
                if (record > 0)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Trả lời " + record + " feedbacks thành công!");
                    this.Window1.Hide();
                    ReloadTargetData();
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message + ex.StackTrace);
            }
        }

    }
}